package cn.jason.ymcc.service.impl;

import cn.jason.ymcc.doc.CourseDoc;
import cn.jason.ymcc.domain.*;
import cn.jason.ymcc.dto.CourseDto;
import cn.jason.ymcc.feign.CourseSearchFeignClient;
import cn.jason.ymcc.feign.MediaFileFeignClient;
import cn.jason.ymcc.mapper.CourseMapper;
import cn.jason.ymcc.result.JSONResult;
import cn.jason.ymcc.service.*;
import cn.jason.ymcc.util.AssertUtil;
import cn.jason.ymcc.util.StrUtils;
import cn.jason.ymcc.vo.CourseDetailInfoVo;
import cn.jason.ymcc.vo.CourseItemVo;
import cn.jason.ymcc.vo.CourseOrderVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jason
 * @since 2022-07-21
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private ICourseDetailService courseDetailService;
    @Autowired
    private ICourseResourceService courseResourceService;
    @Autowired
    private ICourseMarketService courseMarketService;
    @Autowired
    private ICourseTeacherService courseTeacherService;
    @Autowired
    private ICourseTypeService courseTypeService;
    @Autowired
    private ICourseSummaryService courseSummaryService;
    @Autowired
    private CourseSearchFeignClient courseSearchFeignClient;
    @Autowired
    private ICourseChapterService courseChapterService;
    @Autowired
    private MediaFileFeignClient mediaFileFeignClient;

    @Override
    @Transactional
    public void save(CourseDto dto) {
        Course course = dto.getCourse();
        CourseDetail courseDetail = dto.getCourseDetail();
        CourseMarket courseMarket = dto.getCourseMarket();
        CourseResource courseResource = dto.getCourseResource();
        List<Long> teacharIds = dto.getTecharIds();
        //参数校验
        Course courseTmp = selectByName(course.getName());
        AssertUtil.isNull(courseTmp,"课程已被注册！！！");
        //保存课程
        course.setStatus(Course.STATE_OFFLINE);
        course.setLoginId(1L);
        course.setLoginUserName("yhptest1");
        List<Teacher> teachers = teacherService.selectBatchIds(teacharIds);
        StringBuilder sb = new StringBuilder();
        teachers.forEach(teacher -> {
            sb.append(teacher.getName()).append(",");
        });
        course.setTeacherNames(sb.toString());
        insert(course);
        //存课程
        courseDetail.setId(course.getId());
        courseDetailService.insert(courseDetail);
        //保存课程销售
        courseMarket.setId(course.getId());
        courseMarketService.insert(courseMarket);
        //保存课程讲师
        teacharIds.forEach(id->{
            CourseTeacher courseTeacher = new CourseTeacher();
            courseTeacher.setCourseId(course.getId());
            courseTeacher.setTeacherId(id);
            courseTeacherService.insert(courseTeacher);
        });
        //保存课程资源
        courseResource.setCourseId(course.getId());
        courseResourceService.insert(courseResource);
        //初始化课程统计
        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(course.getId());
        courseSummaryService.insert(courseSummary);
        //课程类型表中的课程数+1
        CourseType type = courseTypeService.selectById(course.getCourseTypeId());
        type.setTotalCount(type.getTotalCount() + 1);
        courseTypeService.updateById(type);
    }

    private Course selectByName(String name) {
        Wrapper<Course> tWrapper = new EntityWrapper<Course>();
        tWrapper.eq("name",name);
        return selectOne(tWrapper);
    }

    /**
     * 课程上架
     * @param courseId
     */
    @Override
    public void onLineCourse(Long courseId) {
        //根据课程Id查询课程，判断可是是否存在
        Course course = selectById(courseId);
        AssertUtil.isNotNull(course,"课程为空！！");
        boolean offLine = course.getStatus() == Course.STATE_OFFLINE;
        AssertUtil.isTrue(offLine,"该课程已经上架！");
        //修改课程状态为上架，填写上架时间
        course.setStatus(Course.STATE_ONLINE);
        course.setOnlineTime(new Date());
        updateById(course);
        //保存课程相关内容到Es
        CourseType type = courseTypeService.selectById(course.getCourseTypeId());
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        CourseDoc doc = new CourseDoc();
        //设置需要保存到Es的字段
        BeanUtils.copyProperties(course,doc);
        BeanUtils.copyProperties(courseMarket,doc);
        BeanUtils.copyProperties(courseSummary,doc);
        doc.setCourseTypeName(type.getName());//单独赋值
        String chargeName = courseMarket.getCharge() == 1 ? "免费" : "收费";
        doc.setChargeName(chargeName);

        JSONResult result = courseSearchFeignClient.saveCourse(doc);
        AssertUtil.isTrue(result.isSuccess(),"课程发布失败");
    }

    @Override
    public void offLineCourse(Long courseId) {
        //根据课程Id查询课程，判断可是是否存在
        Course course = selectById(courseId);
        AssertUtil.isNotNull(course,"课程为空!!");

        boolean offLine = course.getStatus() == 1;
        AssertUtil.isTrue(offLine,"该课程已经下架");
        //修改课程状态为下架，填写下架时间
        course.setStatus(0);
        course.setOnlineTime(new Date());
        updateById(course);
        //保存课程相关内容到Es
        CourseType type = courseTypeService.selectById(course.getCourseTypeId());
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        //设置需要保存到Es的字段
        CourseDoc doc = new CourseDoc();
        BeanUtils.copyProperties(course,doc);
        BeanUtils.copyProperties(courseMarket,doc);
        BeanUtils.copyProperties(courseSummary,doc);
        doc.setCourseTypeName(type.getName());//要单独赋值
        String chargeName = courseMarket.getCharge() == 1 ? "免费" : "收费";
        doc.setChargeName(chargeName);

        JSONResult jsonResult = courseSearchFeignClient.deleteCourse(doc);
        AssertUtil.isTrue(jsonResult.isSuccess(),"课程下架失败");
    }

    @Override
    public CourseDetailInfoVo searchCourseDetail(Long courseId) {
        //校验
        AssertUtil.isNotNull(courseId,"请求错误");
        Course course = selectById(courseId);
        AssertUtil.isNotNull(course,"请求错误");
        boolean onLine = course.getStatus() == Course.STATE_ONLINE;
        AssertUtil.isTrue(onLine,"请求错误");

        CourseDetail courseDetail = courseDetailService.selectById(courseId);
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        Wrapper<CourseTeacher> ctwrapper = new EntityWrapper<>();
        ctwrapper.eq("course_id",courseId);
        List<CourseTeacher> courseTeachers = courseTeacherService.selectList(ctwrapper);
        List<Long> teacherIds = courseTeachers.stream().map(teacher -> teacher.getTeacherId()).collect(Collectors.toList());
        List<Teacher> teachers = teacherService.selectBatchIds(teacherIds);
        //查询章节
        Wrapper<CourseChapter> ccwrapper = new EntityWrapper<>();
        ccwrapper.eq("course_id",courseId);
        List<CourseChapter> chapters = courseChapterService.selectList(ccwrapper);
        //每个章节查询对应的视频
        chapters.forEach(chapter->{
            JSONResult jsonResult = mediaFileFeignClient.searchMediaFiles(chapter.getId());
            if(jsonResult.isSuccess() && jsonResult.getData() != null){
                List<MediaFile> fileList = JSONObject.parseArray(jsonResult.getData().toString(), MediaFile.class);
                chapter.getMediaFiles().addAll(fileList);
            }
        });
        CourseDetailInfoVo detai = new CourseDetailInfoVo();
        detai.setCourse(course);
        detai.setCourseChapters(chapters);
        detai.setCourseMarket(courseMarket);
        detai.setCourseSummary(courseSummary);
        detai.setCourseDetail(courseDetail);
        detai.setTeachers(teachers);
        return detai;
    }

    @Override
    public CourseOrderVo courserOrderVo(String courseIds) {
        List<Long> ids = StrUtils.splitStr2LongArr(courseIds);
        Set<Long> SetIds = ids.stream().collect(Collectors.toSet());
        //参数校验
        AssertUtil.isNotEmpty(courseIds,"非法请求");
        //业务判断
        boolean a = ids.size() == SetIds.size();
        AssertUtil.isTrue(a,"非法请求,大莽");
        //根据id查询课程查询销售表
        List<CourseItemVo> courseInfos = new ArrayList<>();
        BigDecimal decimal = new BigDecimal(0);
        for (Long id : SetIds){
            //封装课程和销售
            Course course = selectById(id);
            AssertUtil.isNotNull(course,"非法请求！,大莽");
            //课程不能上线
            boolean online = course.getStatus() == Course.STATE_ONLINE;
            AssertUtil.isTrue(online,"非法请求,大莽!");
            CourseMarket courseMarket = courseMarketService.selectById(id);
            AssertUtil.isNotNull(courseMarket,"雷帝大莽来了!!");
            CourseItemVo courseItemVo = new CourseItemVo(course, courseMarket);
            courseInfos.add(courseItemVo);
            decimal = decimal.add(courseMarket.getPrice());
        }
        //用封装好的list+金额
        return new CourseOrderVo(courseInfos,decimal);
    }

}
